<template>
  <div>
    <div class="title-wrapper">
      <el-page-header @back="goBack" :content="title"> </el-page-header>
    </div>
    <el-form
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="260px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          clearable
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="缩略图上传" prop="uploadFaceImg">
        <el-upload
          ref="uploadFaceImg"
          class="avatar-uploader"
          :action="uploadFaceImgAction"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="formData.keyWord"
          placeholder="请输入关键字"
          clearable
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="简介" prop="synopsis">
        <el-input
          v-model="formData.synopsis"
          type="textarea"
          placeholder="请输入简介"
          :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="newsAuthor">
        <el-input
          v-model="formData.newsAuthor"
          placeholder="请输入作者"
          clearable
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          type="datetime"
          v-model="formData.pubdate"
          value-format="yyyy-MM-dd HH:mm:ss"
          :style="{ width: '100%' }"
          placeholder="请选择发布时间"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="文章来源" prop="newsSource">
        <el-input
          v-model="formData.newsSource"
          placeholder="请输入文章来源"
          clearable
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属专科" prop="belongToSpecialty">
        <el-select
          v-model="formData.belongToSpecialty"
          placeholder="请选择所属专科"
          filterable
          clearable
          :formatter="specialtyStateFormat"
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="(item, index) in depStateOptions"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容">
        <!-- <editor
                    v-model="formData.mainText"
                    :min-height="192"
                /> -->
        <VueUeditorWrap
          :config="editorConfig"
          :destroy="true"
          v-model="formData.mainText"
        />
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import Editor from "@/components/Editor";
import { uploadFileUrl, baseUrl } from "@/api/config";
import {
  listNews,
  getNews,
  delNews,
  addNews,
  updateNews
} from "@/api/operater/news";
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
  components: {
    Editor,
    VueUeditorWrap
  },
  props: [],
  data() {
    return {
      //富文本编辑器
      editorConfig: {
        autoHeightEnabled: false, //编译器不自动被内容撑高
        initialFrameHeight: 350, //初始容器高度
        initialFrameWith: "100%",
        // UEDITOR_HOME_URL: '/UEditor/',
        UEDITOR_HOME_URL: process.env.BASE_URL
          ? process.env.BASE_URL + "UEditor/"
          : "/UEditor/"
      },
      imageUrl: "",
      title: "新增文章",
      formData: {
        title: "",
        thumbnailId: null,
        keyWord: "",
        synopsis: "",
        newsAuthor: "",
        pubdate: null,
        newsSource: "",
        belongToSpecialty: "",
        mainText: "",
        newsState: 0
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur"
          }
        ],
        keyWord: [
          {
            required: true,
            message: "请输入关键字",
            trigger: "blur"
          }
        ],
        synopsis: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur"
          }
        ],
        newsAuthor: [
          {
            required: true,
            message: "请输入作者",
            trigger: "blur"
          }
        ],
        pubdate: [
          {
            required: true,
            message: "请选择发布时间",
            trigger: "change"
          }
        ],
        newsSource: [],
        belongToSpecialty: [
          {
            required: true,
            message: "请选择所属专科",
            trigger: "blur"
          }
        ]
      },
      depStateOptions: null,
      uploadFaceImgAction: uploadFileUrl,
      isUpdate: false
    };
  },
  computed: {},
  watch: {
    formData: {
      handler(newValue, oldValue) {
        console.log(Boolean(newValue.pubdate));
        this.formData.newsState = newValue.pubdate ? 0 : 1;
      },
      deep: true
    }
  },
  created() {
    var id = this.$route.query.newsId;
    if (id) {
      this.isUpdate = true;
      this.title = "编辑文章";
      this._getNews(id);
    }
    this.getDicts("belong_department").then(response => {
      this.depStateOptions = response.data;
    });
  },
  mounted() {},
  methods: {
    specialtyStateFormat(row, column) {
      return this.selectDictLabel(this.depStateOptions, row.belongToSpecialty);
    },
    // ready(editorInstance) {
    //     console.log(`编辑器实例${editorInstance.key}: `, editorInstance)
    // },
    _getNews(id) {
      getNews(id)
        .then(res => {
          console.log(res);
          if (res.code === 200) {
            this.imageUrl = baseUrl(res.data.thumbnailId);
            this.formData = { ...res.data };
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    // 状态字典翻译
    depStateFormat(row, column) {
      // return this.selectDictLabel(this.depStateOptions, row.newsState);
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);s
      if (res.code === 200) {
        this.imageUrl = res.data.fileUrl;
        this.formData.thumbnailId = res.data.id;
      } else {
        this.$message.error(res.msg);
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    submitForm() {
      console.log(this.formData);
      if (!this.isUpdate) {
        this.$refs["elForm"].validate(valid => {
          if (!valid) return;
          // TODO 提交表单
          addNews(this.formData).then(response => {
            if (response.code === 200) {
              this.$message.success(response.msg);
              this.resetForm();
              this.imageUrl = "";
              this.$router.go(-1);
            }
          });
        });
      } else {
        this.$refs["elForm"].validate(valid => {
          if (!valid) return;
          // TODO 提交表单
          updateNews(this.formData).then(response => {
            if (response.code === 200) {
              this.$message.success(response.msg);
              this.resetForm();
              this.imageUrl = "";
              this.$router.go(-1);
            }
          });
        });
      }
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
    }
  }
};
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 300px;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 178px;
  display: block;
}
.title-wrapper {
  padding: 24px;
}
.el-upload__tip {
  line-height: 1.2;
}
.el-form {
  width: 80%;
  margin: 0 auto;
}
</style>
